<!-- src/views/echarts/Histogram.vue -->
<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { useResizeObserver } from '@vueuse/core';

/*
定义父组件输入参数 props，类似于
title: {
  text: '主标题',
  subtext: '父标题'
},
// x轴数据坐标
xAxisData: [location1, location2, location3, location4, location5],
// 多个y轴数据
data: {
  'A': [10, 20, 30, 40, 50],
  'B': [10, 20, 30, 40, 50],
  'C': [10, 20, 30, 40, 50],
  'D': [10, 20, 30, 40, 50],
  'E': [10, 20, 30, 40, 50],
}
*/

// 1. 定义 props
const props = defineProps({
  title: {
    type: Object,
    required: true,
    default: () => ({ text: '', subtext: null })
  },
  xAxisData: {
    type: Array,
    required: true,
    default: () => [],
  },
  dataRef: {
    type: Object,
    required: true,
  },
});

// 2. 引用 chartRef
const chartRef = ref(null);
const seriesData = ref([]);
const keys = ref([]);
// let chartInstance = null;
const chartInstance = ref(null);

// 3. 监听 props.dataRef 更新 seriesData
const updateSeriesData = () => {
  keys.value = Object.keys(props.dataRef);
  seriesData.value = keys.value.map(key => ({
    name: key,
    type: 'bar',
    data: props.dataRef[key],
    markPoint: {
      data: [
        { type: 'max', name: '最大值' },
        { type: 'min', name: '最小值' },
      ]
    }
  }))
}

// 4. 更新图表配置
const updateOption = () => {
  return {
    title: {
      text: props.title.text,
      subtext: props.title.subtext,
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: keys.value,
    },
    toolbox: {
      show: true,
      feature: {
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar'] },
        saveAsImage: { show: true }
      }
    },
    xAxis: {
        type: 'category',
        data: props.xAxisData,
      },
    yAxis: {
      type: 'value',
    },
    series: seriesData.value,
  }
};

// 4. 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance.value = echarts.init(chartRef.value);
    const option = updateOption();
    chartInstance.value.setOption(option);
  }
};

// 5. 使用vueuse/core 的 useResizeObserver
const { resizeObserver } = useResizeObserver(chartRef, () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
}, { disabled: !chartRef.value});

// 6. 挂载时初始化图表
onMounted(async () => {
  updateSeriesData();
  initChart();
});

// 7. 组件卸载处理处理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
});

// 8. 监听 props 变化，更新图表
watch(
  () => props.dataRef,
  () => {
    if (chartInstance.value) {
      updateSeriesData();
      const option = updateOption();
      chartInstance.value.setOption(option);
    }
  },
  {deep: true}
);
</script>

<template>
  <div class="chart-panel" ref="chartRef"></div>
</template>

<style scoped lang="scss">
.chart-panel {
  width: 100%;
  height: 100%;
}
</style>
